package top.ajunnihao.core.web.controller.admin;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.ajunnihao.core.entity.User;
import top.ajunnihao.core.service.UserService;
import top.ajunnihao.core.util.resp.JResp;

import javax.servlet.http.HttpSession;

/**
 * <p>
 * 管理员前端控制器
 * </p>
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    private static final String ADMIN = "ADMIN";

    @Autowired
    private UserService userService;

    @PostMapping("/login.do")
    public Object adminLogin(@RequestBody User user, HttpSession session) {
        // 查询用户
        User loginAdmin = userService.getOne(
            Wrappers.<User>lambdaQuery()
                .eq(User::getAdmin, true)
                .eq(User::getUserNickname, user.getUserNickname())
                .eq(User::getUserPassword, user.getUserPassword())
        );
        if (loginAdmin == null) {
            return JResp.error("用户名或密码错误");
        }

        // 存入 Session
        session.setAttribute(ADMIN, loginAdmin);
        return JResp.ok("登录成功");
    }

    @PostMapping("/logout.do")
    public Object userLogout(HttpSession session) {
        session.removeAttribute(ADMIN);
        return JResp.ok("退出登录成功");
    }

}
